package com.cruise.game.service.impl.agent;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.common.constants.OrderConstants;
import com.cruise.game.mapper.AgentMapper;
import com.cruise.game.mapper.OrderMapper;
import com.cruise.game.mapper.UserMapper;
import com.cruise.game.model.entity.Agent;
import com.cruise.game.model.entity.Order;

import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.model.vo.order.OrderDetailVO;
import com.cruise.game.model.vo.order.OrderListVO;
import com.cruise.game.service.agent.AgentOrderService;
import com.cruise.game.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 代理订单服务实现
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class AgentOrderServiceImpl implements AgentOrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private AgentMapper agentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderService orderService;

    @Override
    public PageResult<OrderListVO> getPendingOrderList(Long userId, Integer page, Integer pageSize) {
        // 查询代理信息
        Agent agent = getAgentByUserId(userId);

        // 构建查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("status", OrderConstants.ORDER_STATUS_PENDING); // 待接单状态
        params.put("gameCategoryId", agent.getGameCategoryId()); // 只查询代理所属游戏分类的订单
        params.put("offset", (page - 1) * pageSize);
        params.put("limit", pageSize);

        // 查询订单列表 - 修改为正确处理Map类型的返回值
        List<Map<String, Object>> orderMaps = orderMapper.selectOrderListByParams(params);
        Long total = orderMapper.countOrderListByParams(params);

        // 转换为VO
        List<OrderListVO> orderListVOs = orderMaps.stream()
                .map(this::convertMapToOrderListVO)
                .collect(Collectors.toList());

        return PageResult.of(orderListVOs, total, page, pageSize);
    }

    @Override
    public PageResult<OrderListVO> getAgentOrderList(Long userId, String status, Integer page, Integer pageSize) {
        // 查询代理信息
        Agent agent = getAgentByUserId(userId);

        // 构建查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("agentId", agent.getId()); // 代理ID

        // 订单状态
        if (StringUtils.isNotBlank(status) && !status.equals("all")) {
            params.put("status", status);
        }

        params.put("offset", (page - 1) * pageSize);
        params.put("limit", pageSize);

        // 查询订单列表 - 修改为正确处理Map类型的返回值
        List<Map<String, Object>> orderMaps = orderMapper.selectOrderListByParams(params);
        Long total = orderMapper.countOrderListByParams(params);

        // 转换为VO
        List<OrderListVO> orderListVOs = orderMaps.stream()
                .map(this::convertMapToOrderListVO)
                .collect(Collectors.toList());

        return PageResult.of(orderListVOs, total, page, pageSize);
    }

    @Override
    public OrderDetailVO getOrderDetail(Long userId, Long orderId) {
        // 查询代理信息
        Agent agent = getAgentByUserId(userId);

        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 如果是待接单状态，不验证代理ID
        if (!OrderConstants.ORDER_STATUS_PENDING.equals(order.getStatus())) {
            // 验证是否为代理自己的订单
            if (order.getAgentId() == null || !order.getAgentId().equals(agent.getId())) {
                throw new ApiException("无权查看此订单");
            }
        }

        // 获取订单详情
        return orderService.getAgentOrderDetail(orderId, agent.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean acceptOrder(Long userId, Long orderId) {
        // 查询代理信息
        Agent agent = getAgentByUserId(userId);

        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证订单状态
        if (!OrderConstants.ORDER_STATUS_PENDING.equals(order.getStatus())) {
            throw new ApiException("订单已被接单或已取消");
        }

        // 验证代理状态
        if (!"available".equals(agent.getStatus())) {
            throw new ApiException("当前状态不可接单");
        }

        // 更新订单信息
        order.setAgentId(agent.getId());
        order.setStatus(OrderConstants.ORDER_STATUS_IN_PROGRESS);
        order.setAcceptedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        return orderMapper.updateById(order) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean startService(Long userId, Long orderId) {
        // 查询代理信息
        Agent agent = getAgentByUserId(userId);

        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证是否为代理自己的订单
        if (order.getAgentId() == null || !order.getAgentId().equals(agent.getId())) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderConstants.ORDER_STATUS_IN_PROGRESS.equals(order.getStatus())) {
            throw new ApiException("订单状态不正确");
        }

        // 这里可以添加一些业务逻辑，比如记录服务开始时间等
        // 简化起见，我们仅更新订单状态（实际上与接单时的状态相同）

        order.setUpdatedAt(LocalDateTime.now());

        return orderMapper.updateById(order) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeOrder(Long userId, Long orderId, String completionImageUrl) {
        // 查询代理信息
        Agent agent = getAgentByUserId(userId);

        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证是否为代理自己的订单
        if (order.getAgentId() == null || !order.getAgentId().equals(agent.getId())) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderConstants.ORDER_STATUS_IN_PROGRESS.equals(order.getStatus())) {
            throw new ApiException("订单状态不正确");
        }

        // 更新订单信息
        order.setStatus(OrderConstants.ORDER_STATUS_COMPLETED);
        order.setCompletionImageUrl(completionImageUrl);
        order.setCompletedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        boolean success = orderMapper.updateById(order) > 0;

        if (success) {
            // 增加代理已完成订单数
            agentMapper.increaseOrdersCompleted(agent.getId());
        }

        return success;
    }

    @Override
    public Map<String, Object> getOrderStatistics(Long userId) {
        // 查询代理信息
        Agent agent = getAgentByUserId(userId);

        Map<String, Object> statistics = new HashMap<>();

        // 今日接单数
        LocalDateTime todayStart = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime todayEnd = LocalDateTime.now().toLocalDate().atTime(23, 59, 59);

        int todayOrders = orderMapper.countByAgentIdAndTimeRange(agent.getId(), todayStart, todayEnd);
        statistics.put("todayOrders", todayOrders);

        // 本月接单数
        LocalDateTime monthStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).toLocalDate()
                .atStartOfDay();
        LocalDateTime monthEnd = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth()).toLocalDate().atTime(23,
                59, 59);

        int monthOrders = orderMapper.countByAgentIdAndTimeRange(agent.getId(), monthStart, monthEnd);
        statistics.put("monthOrders", monthOrders);

        // 待处理订单数
        int pendingOrders = orderMapper.countByAgentIdAndStatus(agent.getId(), OrderConstants.ORDER_STATUS_IN_PROGRESS);
        statistics.put("pendingOrders", pendingOrders);

        // 已完成订单数
        int completedOrders = agent.getOrdersCompleted();
        statistics.put("completedOrders", completedOrders);

        // 本月收入
        BigDecimal monthIncome = orderMapper.sumIncomeByAgentIdAndTimeRange(agent.getId(), monthStart, monthEnd);
        statistics.put("monthIncome", monthIncome != null ? monthIncome : BigDecimal.ZERO);

        // 总收入
        BigDecimal totalIncome = orderMapper.sumIncomeByAgentId(agent.getId());
        statistics.put("totalIncome", totalIncome != null ? totalIncome : BigDecimal.ZERO);

        return statistics;
    }

    /**
     * 根据用户ID获取代理信息
     */
    private Agent getAgentByUserId(Long userId) {
        Agent agent = agentMapper.selectOne(
                new LambdaQueryWrapper<Agent>()
                        .eq(Agent::getUserId, userId)
                        .last("LIMIT 1"));

        if (agent == null) {
            throw new ApiException("代理信息不存在");
        }

        return agent;
    }

    /**
     * 将Map转换为订单列表VO
     */
    private OrderListVO convertMapToOrderListVO(Map<String, Object> orderMap) {
        OrderListVO vo = new OrderListVO();

        // 设置基本属性
        vo.setId(getLongValue(orderMap, "id"));
        vo.setOrderNumber((String) orderMap.get("order_number"));
        vo.setPrice(getBigDecimalValue(orderMap, "price"));
        vo.setStatus((String) orderMap.get("status"));
        vo.setOrderedAt(getDateTimeValue(orderMap, "ordered_at"));
        vo.setAcceptedAt(getDateTimeValue(orderMap, "accepted_at"));
        vo.setCompletedAt(getDateTimeValue(orderMap, "completed_at"));
        vo.setExpectedCompletionTime(getDateTimeValue(orderMap, "expected_completion_time"));

        // 设置服务名称
        vo.setServiceName("游戏服务"); // 实际项目中应查询服务名称

        return vo;
    }

    /**
     * 从Map中获取Long类型值
     */
    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        return null;
    }

    /**
     * 从Map中获取BigDecimal类型值
     */
    private BigDecimal getBigDecimalValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        } else if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        return null;
    }

    /**
     * 从Map中获取DateTime类型值
     */
    private LocalDateTime getDateTimeValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof LocalDateTime) {
            return (LocalDateTime) value;
        }
        return null;
    }
}